<?php 
ini_set('date.timezone','Asia/Shanghai');
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include('/application/libraries/aliyun-dysms-php-sdk/api_demo/SmsDemo.php'); //这个是你下面实例化的类
class Userapi extends CI_Controller {
	/**
	 * 判断递交方法
	 *
	 * @param	IS_POST	//新增
	 * @param	IS_GET	//查询
	 * @param	IS_PUT  //修改
	 * @param	IS_DEL  //删除
	 *
	 * @param	$this->load->model('Model_m');  // 实例 增删改查 的模型
     * @param	$user_IP = $this->Model_m->select('app_auth',$ip_where,'id desc','1,1');  1//app_auth 数据表  2//$ip_where where数组 3//正序倒序  4//limit
	 * 	
     *
	 */

	public function __construct(){
		parent::__construct();
		//header('Content-Type: application/json; charset=utf-8');
		$this->load->helper(array('form', 'url'));
		$this->load->model('Model_m');// 第三方 实例 增删改查 的模型
		// $this->load->model('Model_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Device_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Order_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Config_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Usersweixin_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Recharge_m');// 第三方 实例 增删改查 的模型
		$this->load->library('api/userapi_service');// 用户中间层 实例 增删改查 的模型
		$this->load->library('session');
		
	}
	
	//wifi.qianlh.com/Mobile/Userapi/user_api
	//http://www.mifi.com/Mobile/Userapi/user_api?user_id=10000	 
    public function user_api(){
		$user = $this->session->userdata('user');

    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				
				break;
			case 'POST':
				
				$post['device_sn'] = $this->input->post('device_sn');
				$post['carid'] = $this->input->post('carid');
				$post['mobile'] = $this->input->post('mobile');
				$post['realname'] = $this->input->post('realname');
				$post['username_qq'] = $this->input->post('qq');
				$post['carid_image_z'] = $this->input->post('carid_image_z');
				$post['carid_image_f'] = $this->input->post('carid_image_f');
				$post['carid_image_s'] = $this->input->post('carid_image_s');
				$post['password'] = substr(md5($this->input->post('qq')),0,6);;
				$post['user_id'] = $user[0]['user_id'];
				
				if(empty($post['device_sn'])){
					$data['success'] = error(4010); //请求要求成功返回信息
      				echo _echo($data);
					exit;
				}
		
				
				$carid_image_z = $post['carid_image_z'];
				$carid_image_f = $post['carid_image_f'];
				$carid_image_s = $post['carid_image_s'];				
				
				//匹配出图片的格式
				if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $carid_image_z, $result)){
					$type = $result[2];
					$new_file = "Uploads/carid/".date('Ymd',time())."/";
					if(!file_exists($new_file)) {
						//检查是否有该文件夹，如果没有就创建，并给予最高权限
						mkdir($new_file, 0700);
					}
					$new_file = $new_file.time().".{$type}";
					if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $carid_image_z)))){
						$carid_image['carid_image_z'] = $new_file;
					}else{
						$data['success'] = error(4009); //请求要求成功返回信息
						echo _echo($data);
						exit;
					}
				}
				
				if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $carid_image_f, $result)){
					$type = $result[2];
					$new_file = "Uploads/carid/".date('Ymd',time())."/";
					if(!file_exists($new_file)) {
						//检查是否有该文件夹，如果没有就创建，并给予最高权限
						mkdir($new_file, 0700);
					}

					$new_file = $new_file.time().".{$type}";
					if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $carid_image_f)))){
						$carid_image['carid_image_f'] = $new_file;
					}else{
						$data['success'] = error(4009); //请求要求成功返回信息
						echo _echo($data);
						exit;
					}
				}
				
				if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $carid_image_s, $result)){
					$type = $result[2];
					$new_file = "Uploads/carid/".date('Ymd',time())."/";
					if(!file_exists($new_file)) {
						//检查是否有该文件夹，如果没有就创建，并给予最高权限
						mkdir($new_file, 0700);
					}
					$new_file = $new_file.time().".{$type}";
					if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $carid_image_s)))){
						$carid_image['carid_image_s'] = $new_file;
					}else{
						$data['success'] = error(4009); //请求要求成功返回信息
						echo _echo($data);
						exit;
					}
				}	
				
		      	$post['carid_image'] = $carid_image;

				$data = $this->userapi_service->user_binding_device($post);
				
				$order_on = time(); //订单编号
				
				//获取一天套餐
				// $where_device_oneday_taocan = array('device_sn' => $post['device_sn']);
				// $device_oneday_taocan =  $this->Device_m->select($where_device_oneday_taocan);

				//获取一天套餐
				// if($device_oneday_taocan[0]['experience'] == 0){
				// 	$get_to_oneday_taocan = $this->device_recharge($post['device_sn'],$order_on,29);
				// 	if($get_to_oneday_taocan['result'] == 0){
				// 		$where_get_to_oneday_taocan = array('device_sn' => $post['device_sn']);
				// 		$data_get_to_oneday_taocan['experience']  = 1;
				// 		$data_get_to_oneday_taocan['experience_time']  = date("YmdHis");
				// 		$this->Device_m->update($where_get_to_oneday_taocan,$data_get_to_oneday_taocan);
				// 	}
				// }

				//实名接口调用
				$shiming = $this->shiming_to_device($post['device_sn']);

				echo _echo($data);
				break;

			case 'PUT':
				
				break;
			case 'DELETE':
				
				break;

			default:
				# code...
				break;
		}

		//$this->load->view('mobile/user_api.php');
	}


	/**
	wifi接口错误码	描述
	0	无错误
	70001	用户不存在
	70002	MAC验证失败
	70003	DeviceId未找到
	70004	保存记录出错
	70005	读取数据出错
	70006	设备未购买套餐
	70007	没有订单数据（该错误出现在删除了数据库中的对应套餐。正常情况下，套餐不应该从表中delete）
	70008	JSON数据不正确
	70998	数据库异常
	70999	其他异常
	*/
     
	//充值 //http://www.mifi.com/Mobile/Userapi/user_recharge?device_sn=1546541
	public function user_recharge(){
		//获取微信OPENID 判断登陆 生成用户
		
    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				$get['device_sn'] = $this->input->get('device_sn');

				$device_sn = $get['device_sn'];
				
				$device_where = array('device_sn'=>$get['device_sn']);
				$device_data = $this->Device_m->select($device_where);
				//数据库设备有没存在
				if(empty($device_data)){
					$data['success'] = error(4006); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}

				//查询模块是否连接在线
				$data_api = $this->select_to_device($get['device_sn']);

				$devices = json_decode($data_api,true);
				$devices_api = $devices['DeviceInfo'];
					
				// if($devices_api['DeviceStatus'] == 'ONLINE'){
				// 	$cmd = '06000D030860';
				// 	$package_id = '4U83P45VxaL7eQHJIOuKwQ==';
				// 	$msg = $this->msg_to_device($get['device_sn'],$cmd,$package_id);
				// }

				if($devices_api['DeviceStatus'] == 'OFFLINE'){
					$data['success'] = error(4008); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}


				if($devices_api['DeviceStatus'] == 'UNACTIVE'){
					$data['success'] = error(4007); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}


				if($devices_api['DeviceStatus'] == 'DISABLE'){
					$data['success'] = error(4009); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}

				//查询洗衣机当前订单状态
				$time = time();
				$device_id_where = array('device_id' => $get['device_sn'],'paystate'=>1);
				$result  = $this->Order_m->select($device_id_where,'orderid desc',1);
		
				$worktime = strtotime(isset($result[0]['worktime']));//订单结束时间转成时间戳
				if($worktime>$time){
						$data['success'] = error(4015); //请求要求成功返回信息
						echo _echo($data);
						exit;
				}
				
				//查询洗衣机当前状态
				//$get['device_sn'] = '866666030867114';
				// $result = $this->select_to_xiyiji($get['device_sn']);  //拿到模块返回的状态参数
				// $xiyiji = json_decode($result,true);
				// $devices_api = $xiyiji['success'];

					
				// if($xiyiji['Success'] == 1){
				// 	$msg = $this->msg_to_device($get['device_sn']);
				// 	print_r($msg);die;
				// 	//if($result['result'] != 70006){
				// 		//if($result['result'] != 70007){
				// 			 //if($result['result'] != 70003){
				// 				// $data['success'] = error(4010); //请求要求成功返回信息
				// 				// echo _echo($data);
				// 				// exit;
				// 			 //}
				// 		//}
				// 	//}
				// }else{
				// 	$data['success'] = error(4010); //请求要求成功返回信息
				// 	echo _echo($data);
				// 	exit;
				// }

				

				//$recharge_where = '';
				//$order_by = 'id asc';

				
				
				$data['user'] = $this->session->userdata('user'); 
				$data['recharge_list'] = $this->Recharge_m->select();
				//$data['get_device_meal'] = json_decode($this->get_device_meal()); //套餐
				$data['device_sn'] = $this->userapi_service->device_sn_get($get);
				$data['success'] = success(4000);
				// $data['time'] = $result;
				echo _echo($data);
				break;
			case 'POST':
				
				break;
			case 'PUT':
				
				break;
			case 'DELETE':
				
				break;

			default:
				# code...
				break;
		}
	}


	/**
     * post给洗衣机发送消息
     * @param string $url
     * @param array $post_data
     */
    function msg_to_device($shebei,$cmd,$package_id){
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
		$get_device_productKey_api_where = array('name' => 'productKey');
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
  		$productKey = $productKey[0]['value']; 
        $url = $_SERVER['HTTP_HOST']."/mobile/api/demo/biaozhunxi.php";
        $post_data['device_sn']   = $shebei;
        $post_data['productKey']  = $productKey;
        $post_data['package_id']  = $package_id;
        $post_data['cmd']         = $cmd;

        $postUrl  = $url;
        $curlPost = _echo($post_data);
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称

        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);

		return $data;  
    }



	/**
     * 查询设备是否在线
     * @param string $url
     * @param array $post_data
     */
	
    function select_to_device($shebei){
    	$str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
		$get_device_productKey_api_where = array('name' => 'productKey');
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
  		$productKey = $productKey[0]['value']; 
        $url = $_SERVER['HTTP_HOST']."/mobile/api/demo/index.php";
        $post_data['device_sn']  = $shebei;
        $post_data['productKey']  = $productKey;

        $postUrl  = $url;
        $curlPost = _echo($post_data);
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data;   
    }	


    /**
     * 查询设备是否在线
     * @param string $url
     * @param array $post_data
     */
	
    function select_to_xiyiji($shebei){
    	$str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
		$get_device_productKey_api_where = array('name' => 'productKey');
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
  		$productKey = $productKey[0]['value']; 
        $url = $_SERVER['HTTP_HOST']."/mobile/api/demo/select.php";
        
        $post_data['device_sn']  = $shebei;
        $post_data['productKey']  = $productKey;
        $post_data['package_id']  = 'G7q1/+D+03bvS+DVRn0mEw==';
        $post_data['cmd']  = '06000D010060';


        $postUrl  = $url;
        $curlPost = _echo($post_data);
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data;   
    }

    /**
     * 查询设备洗衣机状态
     * @param string $url
     * @param array $post_data
     */

    function select_to_xiyiji_info($shebei){
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		// $shebei = '866673035753893';
		$get_device_productKey_api_where = array('name' => 'productKey');
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
  		$productKey = $productKey[0]['value']; 
        $select_xiyiji_info_url_api_where = array('name' => 'select_xiyiji_url');
        $select_xiyiji_info_url  = $this->Config_m->select($select_xiyiji_info_url_api_where);
  		// $url = "http://115.29.212.220:9797/api/v1/parse/command";
		$url = $select_xiyiji_info_url[0]['value'];
		
        //数据json化。	
        //00表示洗衣机；
		//0C是昌威洗衣机主板洗衣机

  		// 更多命令类型说明：
		// 命令类型	编号	备注
		// 模块请求命令	00	模块主动上报命令（可平台主动下发）
		// 查询状态命令	01	查询设备状态/报警状态等
		// 设置参数命令	03	设置厂家ID和唯一标识等
		// 启动程序命令	05	快速/标准/大物洗等
		// 确认收到回复命令	07	通知主板已收到回复消息
		
	    $header[] = 'Content-Type: application/json;charset=utf-8';
		// $post_data = '{"product":{"type":"00","name":"0D"},"command":{"type":"01","name":"00"},"agrs":[],"needResp":true}';
		$post_data['product']  = array('type' => '00', 'name' => '0D');
		$post_data['command']  = array('type' => '01', 'name' => '00');
		$post_data['agrs']     = array();
		$post_data['needResp'] = true;
		
	 	$curlPost = json_encode($post_data);
		// print_r($post_data);die;
		// $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		if($data['success'] == 1){
			$msg['success'] = $data['success'];
			$msg['content'] = json_decode($data['content'], true);
			return $msg;
		}
    }


    /**
     * 查询设备222
     * @param string $url
     * @param array $post_data
     */

    function select_to_device2($shebei){
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		// $shebei = '866673035753893';
		$get_device_productKey_api_where = array('name' => 'productKey');
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
  		$productKey = $productKey[0]['value']; 
        $select_device_info_url_api_where = array('name' => 'select_device_url');
        $select_device_info_url  = $this->Config_m->select($select_device_info_url_api_where);
  		// $url = "http://115.29.212.220:9797/api/v1/parse/command";
		$url = $select_device_info_url[0]['value'];
		// print_r($url);die;
        //数据json化。	
        //00表示洗衣机；
		//0C是昌威洗衣机主板洗衣机

  		// 更多命令类型说明：
		// 命令类型	编号	备注
		// 模块请求命令	00	模块主动上报命令（可平台主动下发）
		// 查询状态命令	01	查询设备状态/报警状态等
		// 设置参数命令	03	设置厂家ID和唯一标识等
		// 启动程序命令	05	快速/标准/大物洗等
		// 确认收到回复命令	07	通知主板已收到回复消息
		
	    $header[] = 'Content-Type: application/json;charset=utf-8';
		// $post_data = '{"product":{"type":"00","name":"0D"},"command":{"type":"01","name":"00"},"agrs":[],"needResp":true}';
		$post_data['product']  = array('type' => '00', 'name' => '0D');
		$post_data['command']  = array('type' => '01', 'name' => '00');
		$post_data['agrs']  = '';
		$post_data['needResp']  = true;
		
	 	$curlPost = json_encode($post_data);
		// print_r($post_data);die;
		// $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		if($data['success'] == 1){
			$msg['success'] = $data['success'];
			$msg['content'] = json_decode($data['content'], true);
			return $msg;
		}
    }	




    //添加设备
  //   function tianjia(){
	 //    set_time_limit(0);
	 //    $get_device_productKey_api_where = array('name' => 'productKey');
		// // $get_device_info_signkey_api_where = array('name' => 'signkey');

		// // $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		// $productKey  = $this->Config_m->select($get_device_productKey_api_where);
		// // $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  // //       $get_device_info_url = $get_device_info_url[0]['value']; 
  // 		$productKey = $productKey[0]['value']; 
  // //      	$signkey = $signkey[0]['value'];
  		
	 //    $shebei = $this->input->post('shebei');
	 //    $data = explode(",",$shebei);
	 //    $datas = $this->add_to_device($data);
	    
	 //    foreach ($datas as $key => $value) {
	 //    		$devices = json_decode($value,true);
	 //    		if($devices['Success'] == 1){
	 //    			$device['device_sn']= $devices['DeviceName'];
	 //    			$device['user_id']  = 1;
	 //    			$device['agent1']   = 1;
	 //    			$device['addtime']  = date('y-m-d h:i:s',time());
	 //    			$device['ProductKey']=$productKey;
		// 			$device['DeviceSecret']=$devices['DeviceSecret'];
	 //    			$this->Device_m->insert($device);
	 //    		}
		// 	}
		// //print_r($device);
		// $sess['success'] = success('4000');	
	 //    echo _echo($sess);
  //   }
    public function adds(){
    	$data = array(
    	##############  设备号 ##############	

    	);
    foreach ($data as $key => $value) {
    	// print_r($value);exit;
    	// $aa = $this->tianjia($value);
    	// $aa = $this->xiugai($value);
    	// print_r($aa);exit;
    }
    }

    public function tianjia($device){
    	
    	set_time_limit(0);
    	$device_where = array('device_sn'=>$device);
		$device_data = $this->Device_m->select($device_where);
		$get_device_productKey_api_where = array('name' => 'productKey');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
		// $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  		$productKey = $productKey[0]['value']; 

    	if(!empty($device_data)){
				// $json_api_cha_xun_she_bei['Code']	 =  "0";	
				// $json_api_cha_xun_she_bei['Data']    = array('devicename' => $device_data[0]['device_sn'],'storeid' => '','storename' => '','businessid' => '','devicedata' => array('productkey' => $device_data[0]['ProductKey'],'devicename' => $device_data[0]['device_sn'],'devicesecret' => $device_data[0]['DeviceSecret']),'offlinenums'=>array('sig_code' => '','kuai_code' => '','std_code' => '','big_code' => '','jiawen_code' => ''));
				// $json_api_cha_xun_she_bei['Msg']	 =  '';

				echo _echo($device_data);
				//print_r(json_encode($json_api_cha_xun_she_bei));die;
			}else{
				
				// $cha_xun_she_bei = $this->select_to_device($data['IMEI']);
				// $json_cha_xun_she_bei = json_decode($cha_xun_she_bei, true);
				// if($json_cha_xun_she_bei['Success'] == ''){
				// 	$datas['success'] = success(4010);
				//     $datas['error'] = 'not this IMEI';
				//     echo _echo($datas);
				//     exit;
				// }else{
					//没有设备，添加新的设备
					$add_she_bei = $this->add_to_device($device);

					$json_api_add_she_bei = json_decode($add_she_bei, true);
					$device = array();
					if($json_api_add_she_bei['Success'] == 1){
						
						$device['device_sn']= $json_api_add_she_bei['DeviceName'];
		    			$device['user_id']  = 1;
		    			$device['agent1']   = 1;
		    			$device['jihuo']   = 1;
		    			$device['addtime']  = date('y-m-d h:i:s',time());
		    			$device['ProductKey']=$productKey;
						$device['DeviceSecret']=$json_api_add_she_bei['DeviceSecret'];


						require_once 'mobile/example/phpqrcode/phpqrcode.php';
				    	// $device_sn = $device;
				    	$url = "http://qt.hiberbest.com/Mobile/index.html?device_sn=".$device['device_sn'];
				        $url = urldecode($url);
				        $qr_code_path = 'uploads/QRcodeDevice/'.date("Y-m-d").'/';
				        if (!file_exists($qr_code_path)) {
				            mkdir($qr_code_path);
				        }
				        /* 生成二维码 */
				        $qr_code_file = $qr_code_path.$device['device_sn'].'.png';
				        QRcode::png($url, $qr_code_file, 'H', 6,6);//最后一个6是控制白边大小
				        $background = "mobile/font/back.png";
				        $logo = "mobile/font/logo.png";
				        $this->mark_photo($qr_code_file,$device['device_sn'],$logo,$qr_code_file);
				        
				        // $where = array('device_sn'=>$device);
				        $device['QRcode'] = "http://qt.hiberbest.com/".$qr_code_file;
				        // return $arr;
				        // $device_data = $this->Device_m->update($where,$arr);
// print_r($device);die;

						// $url = "http://".$_SERVER['HTTP_HOST']."/Mobile/index.html?device_sn=".$device['device_sn'];
				  //       $url = urldecode($url);
				  //       $qr_code_path = 'uploads/QRcodeDevice/'.date("Y-m-d").'/';
				  //       if (!file_exists($qr_code_path)) {
				  //           mkdir($qr_code_path);
				  //       }
				  //       /* 生成二维码 */
				  //       $qr_code_file = $qr_code_path.$device['device_sn'].'.png';
				  //       QRcode::png($url, $qr_code_file, 'H', 6,6);//最后一个6是控制白边大小
				  //       $background = "mobile/font/back.png";
				  //       $logo = "mobile/font/logo.png";
				  //       $this->mark_photo($qr_code_file,$device['device_sn'],$logo,$qr_code_file);

				  //       $device['QRcode']   = "http://".$_SERVER['HTTP_HOST'].'/'.$qr_code_file;

						$this->Device_m->insert($device);

						//print_r($add_she_bei);die;
					}
				// }

				// $json_api_cha_xun_she_bei['Code']	 =  "0";	
				// $json_api_cha_xun_she_bei['Data']    = array('devicename' => $json_api_add_she_bei['DeviceName'],'storeid' => '','storename' => '','businessid' => '','devicedata' => array('productkey' => $productKey,'devicename' => $json_api_add_she_bei['DeviceName'],'devicesecret' => $json_api_add_she_bei['DeviceSecret']),'offlinenums'=>array('sig_code' => '','kuai_code' => '','std_code' => '','big_code' => '','jiawen_code' => ''));
				// $json_api_cha_xun_she_bei['Msg']	 =  '';
				echo '<br/>';
				echo _echo($device_data);

				//print_r(json_encode($json_api_cha_xun_she_bei));die;
			}
		}
    
	public function xiugai($device){
    	
    	set_time_limit(0);
    	$device_where = array('device_sn'=>$device);
		$device_data = $this->Device_m->select($device_where);
		$get_device_productKey_api_where = array('name' => 'productKey');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
		// $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  		$productKey = $productKey[0]['value']; 

    	if(empty($device_data['agent2'])){
				$agent2 = array('agent2' => 10030);;
				$where  = array('device_sn' => $device);
				$data  = $this->Device_m->update($where,$agent2);
				echo '<br/>';
				print_r($data);
				// $json_api_cha_xun_she_bei['Code']	 =  "0";	
				// $json_api_cha_xun_she_bei['Data']    = array('devicename' => $device_data[0]['device_sn'],'storeid' => '','storename' => '','businessid' => '','devicedata' => array('productkey' => $device_data[0]['ProductKey'],'devicename' => $device_data[0]['device_sn'],'devicesecret' => $device_data[0]['DeviceSecret']),'offlinenums'=>array('sig_code' => '','kuai_code' => '','std_code' => '','big_code' => '','jiawen_code' => ''));
				// $json_api_cha_xun_she_bei['Msg']	 =  '';

				echo _echo($device_data);
				//print_r(json_encode($json_api_cha_xun_she_bei));die;
			}
				
			
		}
	// public function ceshi(){
	// 	$aa = $this->db->where(array('name'=>'dns'))->get('mifi_config')->row_array();
 //    	print_r($aa['value']);exit;
		
	// }
    public function erweima($device){
    	require_once 'mobile/example/phpqrcode/phpqrcode.php';
    	$device_sn = $device;
    	$url = "http://qt.hiberbest.com/Mobile/index.html?device_sn=".$device_sn;
        $url = urldecode($url);
        $qr_code_path = 'uploads/QRcodeDevice/'.date("Y-m-d").'/';
        if (!file_exists($qr_code_path)) {
            mkdir($qr_code_path);
        }
        /* 生成二维码 */
        $qr_code_file = $qr_code_path.$device_sn.'.png';
        QRcode::png($url, $qr_code_file, 'H', 6,6);//最后一个6是控制白边大小
        $background = "mobile/font/back.png";
        $logo = "mobile/font/logo.png";
        $this->mark_photo($qr_code_file,$device_sn,$logo,$qr_code_file);
        
        // $where = array('device_sn'=>$device);
        $arr['QRcode'] = "http://qt.hiberbest.com/".$qr_code_file;
        return $arr;
        // $device_data = $this->Device_m->update($where,$arr);
    }
    //拼接图片,logo,文字
    private function mark_photo($background,$text,$logo,$filename){
        $back=imagecreatefrompng($background);
        $color=imagecolorallocate($back,0,0,0);
        $logo=imagecreatefrompng($logo);
        $logo_w=imagesx($logo);
        $logo_h=imagesy($logo);
        $font="mobile/font/STYH.otf"; // 字体文件
        //imagettftext只认utf8字体，所以用iconv转换
        imagettftext($back, 21, 0, 40, 337, $color, $font, $text);//调二维码中字体位置
        //执行合成调整位置
        imagecopyresampled($back, $logo, 139,140, 0, 0, 65, 65, $logo_w, $logo_h);//调中间logo位置
        imagejpeg($back,$filename);       
        imagedestroy($back);
        imagedestroy($logo);
    }

    //获取阿里云洗衣机设备号码_接口
    public function select_to_device_list(){
		//查询套餐]
    	header("Connection: close");
    	require_once 'mobile/example/phpqrcode/phpqrcode.php';

		$data = $this->input->get(); //接到get请求 E30E65952253975D7C83F9AE4C200D77
		$ip = $_SERVER['REMOTE_ADDR'];
		$file  = 'log.txt';//要写入文件的文件名（可以是任意文件名），如果文件不存在，将会创建一个
		$content =date("Y/m/d h:i:sa").'访问IP：'.$ip.json_encode($data)."\r\n";
		if($f  = file_put_contents($file, $content,FILE_APPEND)){// 这个函数支持版本(PHP 5) 
			//echo "写入成功。<br />";
		}
		//	print($ip);die;
		
		//print_r($data);die;

		// if(empty($data['IMEI'])){
		// 	$datas['success'] = success(4010);
		//     $datas['error'] = 'not this IMEI';
		//     echo json_encode($data,true);
		// }
		$get_device_productKey_api_where = array('name' => 'productKey');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
		// $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  		$productKey = $productKey[0]['value']; 

		$sinkey = $data['IMEI'].$data['company'].$data['pssword'].$data['timestamp'];
		//$sinkey = $data['IMEI'].$data['company'].$data['pssword'];
		$sign = strtoupper(MD5($sinkey));
		if($sign == $data['sign']){
			$device_data = array();
			$device_where = array('device_sn'=>$data['IMEI']);
			$device_data = $this->Device_m->select($device_where);
			
			//print_r($device_data);die;

			if(!empty($device_data)){
				$json_api_cha_xun_she_bei['Code']	 =  "0";	
				$json_api_cha_xun_she_bei['Data']    = array('devicename' => $device_data[0]['device_sn'],'storeid' => '','storename' => '','businessid' => '','devicedata' => array('productkey' => $device_data[0]['ProductKey'],'devicename' => $device_data[0]['device_sn'],'devicesecret' => $device_data[0]['DeviceSecret']),'offlinenums'=>array('sig_code' => '','kuai_code' => '','std_code' => '','big_code' => '','jiawen_code' => ''));
				$json_api_cha_xun_she_bei['Msg']	 =  '';

				echo _echo($json_api_cha_xun_she_bei);
				//print_r(json_encode($json_api_cha_xun_she_bei));die;
			}else{
				// $cha_xun_she_bei = $this->select_to_device($data['IMEI']);
				// $json_cha_xun_she_bei = json_decode($cha_xun_she_bei, true);
				// if($json_cha_xun_she_bei['Success'] == ''){
				// 	$datas['success'] = success(4010);
				//     $datas['error'] = 'not this IMEI';
				//     echo _echo($datas);
				//     exit;
				// }else{
					//没有设备，添加新的设备
					$add_she_bei = $this->add_to_device($data['IMEI']);
					$json_api_add_she_bei = json_decode($add_she_bei, true);

					if($json_api_add_she_bei['Success'] == 1){
						$device['device_sn']= $json_api_add_she_bei['DeviceName'];
		    			$device['user_id']  = 1;
		    			$device['agent1']   = 1;
		    			$device['jihuo']   = 1;
		    			$device['addtime']  = date('y-m-d h:i:s',time());
		    			$device['ProductKey']=$productKey;
						$device['DeviceSecret']=$json_api_add_she_bei['DeviceSecret'];

						//查询地址
						$dataurl = $this->db->where(array('name'=>'dns'))->get('mifi_config')->row_array();
						$url = $dataurl['value']."/Mobile/index.html?device_sn=".$device['device_sn'];

				        $url = urldecode($url);
				        $qr_code_path = 'uploads/QRcodeDevice/'.date("Y-m-d").'/';
				        if (!file_exists($qr_code_path)) {
				            mkdir($qr_code_path);
				        }
				        /* 生成二维码 */
				        $qr_code_file = $qr_code_path.$device['device_sn'].'.png';
				        \QRcode::png($url, $qr_code_file, 'H', 6,6);//最后一个6是控制白边大小
				        $background = "mobile/font/back.png";
				        $logo = "mobile/font/logo.png";
				        $this->mark_photo($qr_code_file,$device['device_sn'],$logo,$qr_code_file);
				        
				        $device['QRcode']   = $dataurl['value'].'/'.$qr_code_file;
						$this->Device_m->insert($device);

						//print_r($add_she_bei);die;
					}
				// }

				$json_api_cha_xun_she_bei['Code']	 =  "0";	
				$json_api_cha_xun_she_bei['Data']    = array('devicename' => $json_api_add_she_bei['DeviceName'],'storeid' => '','storename' => '','businessid' => '','devicedata' => array('productkey' => $productKey,'devicename' => $json_api_add_she_bei['DeviceName'],'devicesecret' => $json_api_add_she_bei['DeviceSecret']),'offlinenums'=>array('sig_code' => '','kuai_code' => '','std_code' => '','big_code' => '','jiawen_code' => ''));
				$json_api_cha_xun_she_bei['Msg']	 =  '';

				echo _echo($json_api_cha_xun_she_bei);
				//print_r(json_encode($json_api_cha_xun_she_bei));die;
			}
		}else{
			$datas['success'] = success(4014);
		    $datas['error'] = 'sign is error';
		    echo _echo($datas);
		    exit;
		}
    	
	}


	/**
     * post添加设备
     * @param string $url
     * @param array $post_data
     */
    function add_to_device($shebei){
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
		$get_device_productKey_api_where = array('name' => 'productKey');
		$productKey  = $this->Config_m->select($get_device_productKey_api_where);
  		$productKey = $productKey[0]['value']; 
        $url = $_SERVER['HTTP_HOST']."/mobile/api/demo/add_one.php";
        $post_data['device_sn']  = $shebei;
        $post_data['productKey']  = $productKey;

        $postUrl  = $url;
        $curlPost = _echo($post_data);
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称

        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);

		return $data;  
    }


    /**
     * 查询设备
     * @param string $url
     * @param array $post_data
     */
	
  //   function select_to_device_api() {
  //       $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
  //       $url = $_SERVER['HTTP_HOST']."/mobile/Userapi/select_to_device_list";

       
  //       $key = '123456';
  //       $ts = time();
  //       $sinkey = $key.$ts;
  //       $post_data['ts']    = $ts;
  //       $post_data['key']   = $key;
  //       $post_data['sinkey']   = MD5(MD5($sinkey));

  //       $postUrl  = $url;
  //       $curlPost = _echo($post_data);
  //       $ch = curl_init();//初始化curl
  //       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
  //       // curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
  //       curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  //       curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
  //       //curl_setopt($ch, CURLOPT_HEADER, false);
  //       curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
  //       curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
  //       curl_setopt($ch, CURLOPT_POST, true);//post提交方式
  //       curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  //       $datas = curl_exec($ch);//运行curl 当前套餐名称
  //       print_r($datas);die;
  //       $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
  //       curl_close($ch);
		// $data = json_decode($datas, true);

		// return $data;  
  //   }


	public function package_list(){
		//查询套餐
		$data['get_device_meal'] = json_decode($this->get_device_meal()); //套餐
		echo _echo($data);
	}

	
	//审核返回 //http://wifi.qianlh.com/Mobile/Userapi/user_IDcard_verify?status=0&user_id=10000
	// public function user_IDcard_verify(){
	// 	//审核返回  接到值,修改本地用户递交资料状态
	// 	 $status = $this->input->get('status');
	// 	 $user_id = $this->input->get('user_id');
	// 	 if($status == 1){
	// 	 	//实名验证通过 1  修改用户表shiming_tongguo = 1
	// 	 	$data['status'] =  1;
	// 	 	$data['user_id'] =  $user_id;
	// 	 	echo _echo($data);
	// 	 }else{
	// 	 	//实名验证未通过 2  修改用户表shiming_tongguo = 2
	// 	 	$data['status'] =  0;
	// 	 	$data['user_id'] = $user_id;
	// 	 	echo _echo($data);
	// 	 }	
	// }


	
	public function weixin_login(){
		$sess_user = $this->session->userdata('user');
		 if($sess_user){
			$url = $this->input->get('url');
			if($url){
				echo '<script>';
				echo 'window.location.href="'.$url.'"';
				echo '</script>';
			}
			exit;
		}

		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			$this->session->unset_userdata('user');
            if(!$this->session->userdata('user')){
				//先写死在这里，后期改到数据库
				$appid_where = array('name' => 'appid');
				$secret_where = array('name' => 'secret');
				$appid  = $this->Config_m->select($appid_where);
				$secret  = $this->Config_m->select($secret_where);
				
		       	$appid = $appid[0]['value']; 
		       	$secret = $secret[0]['value'];

                if(!isset($_GET['code'])){
                    $url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; //这是要回调地址可以有别的写法
                    redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                    //重定向到以上网址,这是微信给的固定地址.必须格式一致
                }else{
                    //回调成功,获取code,再做请求,获取openid
					$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$_GET['code']}&grant_type=authorization_code";
					$ch = curl_init();//初始化curl        
					curl_setopt($ch, CURLOPT_TIMEOUT, 300);//设置超时
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
					curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
					curl_setopt($ch, CURLOPT_HEADER, FALSE);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);         
					$res = curl_exec($ch);//运行curl，结果以jason形式返回            
					$data = json_decode($res,true);
					curl_close($ch);
					
					if(!isset($data['openid']) || !isset($data['access_token'])){
						$this->weixin_login();
					}
					
					$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN";
			        $ch = curl_init();//初始化curl
			        curl_setopt($ch, CURLOPT_TIMEOUT,300);//设置超时
			        curl_setopt($ch, CURLOPT_URL, $url);
			        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
			        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
			        curl_setopt($ch, CURLOPT_HEADER, FALSE);
			        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);         
			        $res = curl_exec($ch);//运行curl，结果以jason形式返回            
			        $data = json_decode($res,true);
				
			        curl_close($ch);
					
			        $this->thirdlogin($data);
					$this->session->userdata('user');
					$url = $this->input->get('url');
					if($url){
						header("Location:".$url.""); 
					}
                }
            }else{
				$this->session->userdata('user');
				$url = $this->input->get('url');
				if($url){
					header("Location:".$url.""); 
				}
			}
        }
	}

	public function thirdlogin($data){
		$weixin_user=$this->Usersweixin_m->select(array('openid'=>$data['openid']));
		if($weixin_user){
			$user=$this->Users_m->select(array('user_id'=>$weixin_user[0]['user_id']));
			$this->session->set_userdata(array('user'=>$user));
		}else{
			$user_id=$this->Users_m->insert(array('nickname'=>$data['nickname'],'reg_time'=>date('Y-m-d H:i:s'),'weixin'=>1));
			$this->Usersweixin_m->insert(array('user_id'=>$user_id,'openid'=>$data['openid']));
			$user=$this->Users_m->select(array('user_id'=>$user_id));
			$this->session->set_userdata(array('user'=>$user));
		}
	}
	
	//佣金计算 
	// function yongjin(){
	// 	$where = array('paystate' => 1);
	// 	$orders = $this->Model_m->select('order',$where);
	// 	$device_ids = array();

	// 	foreach ($orders as $key => $value) {
	// 		$device_ids[$key] = $value;
	// 	}
		
	// 	$devices = array();
	// 	foreach ($device_ids as $k => $val) {
	// 		$where_device = array('device_sn' => $val['device_id']);
	// 		$devices = $this->Model_m->select('device',$where_device);
	// 		$devicesa = $devices[0];
	// 		if($devicesa['agent1'] != null){
	// 			$data['agent_user_id'] = $devicesa['agent1'];
	// 			$data['order_id'] = $val['order_on'];
	// 			$data['addtime'] = $val['starttime'];
	// 			$data['device_sn'] = $val['device_id'];
	// 			$data['money'] = $val['order_money']*0.1;
	// 			if($val['goods_on'] == 1){
	// 				$data['flow'] = '1个月流量套餐';
	// 			}
	// 			if($val['goods_on'] == 2){
	// 				$data['flow'] = '3个月流量套餐';
	// 			}
	// 			if($val['goods_on'] == 3){
	// 				$data['flow'] = '6个月流量套餐';
	// 			}
	// 			if($val['goods_on'] == 4){
	// 				$data['flow'] = '12个月流量套餐';
	// 			}
	// 			$data['addtime2'] = strtotime($data['addtime']);
	// 			$devices = $this->Model_m->insert('commission',$data);
	// 		}
			
	// 		if($devicesa['agent2'] != null){
	// 			$data['agent_user_id'] = $devicesa['agent2'];
	// 			$data['order_id'] = $val['order_on'];
	// 			$data['addtime'] = $val['starttime'];
	// 			$data['device_sn'] = $val['device_id'];
	// 			$data['money'] = $val['order_money']*0.1;
	// 			if($val['goods_on'] == 1){
	// 				$data['flow'] = '1个月流量套餐';
	// 			}
	// 			if($val['goods_on'] == 2){
	// 				$data['flow'] = '3个月流量套餐';
	// 			}
	// 			if($val['goods_on'] == 3){
	// 				$data['flow'] = '6个月流量套餐';
	// 			}
	// 			if($val['goods_on'] == 4){
	// 				$data['flow'] = '12个月流量套餐';
	// 			}
	// 			$data['addtime2'] = strtotime($data['addtime']);
	// 			$devices = $this->Model_m->insert('commission',$data);
	// 		}
	// 	}
	// } 
	
	
	/**
     * post进行开通1天体验套餐请求
     * @param string $url
     * @param array $post_data
     */

	// function device_recharge($device_id,$order_no,$packages) 
	// {
	// 	$str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
 //      	$length = strlen($device_id);
	// 	// if($length != 16){
	// 	// 	$device_id = "0".$device_id."";
	// 	// }
	// 	$get_device_info_url_api_where = array('name' => 'device_recharge_url');
	// 	$get_device_info_uid_api_where = array('name' => 'uid');
	// 	$get_device_info_signkey_api_where = array('name' => 'signkey');

	// 	$device_recharge_url  = $this->Config_m->select($get_device_info_url_api_where);
	// 	$uid  = $this->Config_m->select($get_device_info_uid_api_where);
	// 	$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        
 //        $device_recharge_url = $device_recharge_url[0]['value']; 
 //       	$id = $uid[0]['value']; 
 //       	$signkey = $signkey[0]['value'];
       	
 //        $url = $device_recharge_url;	
 //        $time = 	time();
 //        $post_data['password']         = $signkey;
 //        $post_data['timestamp']        = $time;
 //        $post_data['username']         = $id;
 //        $post_data['simId']            = $device_id;
 //        $post_data['mealId']           = $packages;
 //        $post_data['countNum']         = 1;

 //        $data = 'mealId'.$post_data['mealId'].'password'.$post_data['password'].'simId'.$post_data['simId'].'timestamp'.$post_data['timestamp'].'username'.$post_data['username'];
        
 //        $key = MD5($data);
 //        $keys = substr($key, 0, 16);
	// 	$post_data['key']      = $keys;

 //        //$header[] = 'Content-Type: text/html;charset=UTF-8';
 //        $postUrl  = $url;
 //        $curlPost =  $post_data;
 //        //print_r($data);die;
 //        $ch = curl_init();//初始化curl
 //        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
 //        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
 //        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
 //        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
 //        //curl_setopt($ch, CURLOPT_HEADER, false);
 //        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
 //        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
 //        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
 //        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
 //        $data = curl_exec($ch);//运行curl
	// 	//print_r($data);die;
 //        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
 //        curl_close($ch);
            
 //        return  json_decode($data, true);
 //    }
	
	
    /**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */
  //   function get_device($device_id) {
  //       $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
  //     	$get_device_info_url_api_where = array('name' => 'get_device_info_url');
		// $get_device_info_uid_api_where = array('name' => 'uid');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $length = strlen($device_id);
		// if($length != 16){
		// 	$device_id = "0".$device_id."";
		// }

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		// $uid  = $this->Config_m->select($get_device_info_uid_api_where);
		// $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  //      	$uid = $uid[0]['value']; 
  //      	$signkey = $signkey[0]['value'];
       	
  //       $url = $get_device_info_url;

  //       $post_data['id']         = $uid;
  //       $post_data['ts']         = time();
  //       $post_data['device_id']  = $device_id;
		// //$post_data['order_no']   = time();
  //       //$post_data['packages']   = array('package_id' =>2,'count' =>1,'start_time' =>-1);
		
  //       $sign = hash_hmac('sha512', _echo($post_data), $signkey);
  //       $header[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
  //       $header[] = 'sign:'.$sign;
  //       $header[] = 'uid:'.$uid;
  //       $postUrl = $url;
  //       $curlPost = _echo($post_data);
        
  //       $ch = curl_init();//初始化curl
  //       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
  //       curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
  //       curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  //       curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
  //       //curl_setopt($ch, CURLOPT_HEADER, false);
  //       curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
  //       curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
  //       curl_setopt($ch, CURLOPT_POST, true);//post提交方式
  //       curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  //       $data = curl_exec($ch);//运行curl
  //       $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
  //       curl_close($ch);
            
  //       return json_decode($data, true);
  //   }

    //多个查询设备状态
  //   function chaxun(){
	 //    set_time_limit(0);
		// $shebei = array(
		// // '8986031748204893516'
		// );
		// $data = array();

	 //    foreach ($shebei as $key => $value) {
	 //    	//$data[$value] = $this->device_recharge('8986031748204893516','1525405573350','DFCD6E367D884E0F98118927DF41AB0A');
		//    //$data[$value] = $this->device_recharge($value);
		   
		// }
	 //    echo '<pre>';	
	 //    print_r($data);		

  //   }

    //单个查询设备状态
  //   function chaxun2(){

		// $shebei = $this->input->get('sn');

		// $data = $this->chaxun_to_device($shebei);
		
	 //    echo '<pre>';
	 //    $data['youxiaoqi'] = date("Y-m-d H:i:s",$data['last_expire_date'] / 1000);
	    	
	 //    print_r($data);
  //   }


    //取所有设备
    function shiming(){
    	ini_set('max_execution_time', '0');
		$get_device_where = array('jihuo' => 1);
		$shebei  = $this->Device_m->select($get_device_where);
	    foreach ($shebei as $key => $value) {
	    	if(!empty($value['user_id']) or $value['user_id'] != 10000){
	    		$data[] = $this->shiming_to_device($value['device_sn']);
	    	}
		}
		
	    echo '<pre>';	
	    print_r($data);		

    }

    //通过用户id获取单个设备信息
	//user_id		用户id
	public function getDeviceByuserid(){
		$sess_user=$this->session->userdata('user');
		if(IS_GET){
			if($sess_user){
				$this->load->model('Device_m');
				$where['user_id']=$sess_user[0]['user_id'];
				$Device=$this->Device_m->select($where);
				$Device_data['success'] = success('4000');	  
				$Device_data['Device'] = $Device;
			    echo _echo($Device_data);
			    exit;
			}else{
				$data['success'] = error('4008');	    	   	
			    echo _echo($data);
			    exit;
			}
	    }else{
			$data['success'] = error('4008');	    	   	
		    echo _echo($data);
		    exit;
		}
		
	}

	/**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */
  //   function device_auth($device_id) {
  //       $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		// //$device_id = $this->input->get('device_id');
  //     	$length = strlen($device_id);
		// if($length != 16){
		// 	$device_id = "0".$device_id."";
		// }
		
		// $get_device_info_url_api_where = array('name' => 'device_auth');

		// $get_device_info_uid_api_where = array('name' => 'uid');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		// $uid  = $this->Config_m->select($get_device_info_uid_api_where);
		// $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  //      	$uid = $uid[0]['value']; 
  //      	$signkey = $signkey[0]['value'];
       	
  //       $url = $get_device_info_url;

  //       $post_data['id']         = $uid;
  //       $post_data['ts']         = time();
  //       $post_data['userName']   = 'user001';
  //       $post_data['device_id']  = $device_id;
		
  //       $sign = hash_hmac('sha512', _echo($post_data), $signkey);
  //       $header[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
  //       $header[] = 'sign:'.$sign;
  //       $header[] = 'uid:'.$uid;
  //       $postUrl  = $url;
  //       $curlPost = _echo($post_data);
        
  //       $ch = curl_init();//初始化curl
  //       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
  //       curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
  //       curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  //       curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
  //       //curl_setopt($ch, CURLOPT_HEADER, false);
  //       curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
  //       curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
  //       curl_setopt($ch, CURLOPT_POST, true);//post提交方式
  //       curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  //       $datas = curl_exec($ch);//运行curl 当前套餐名称
        
  //       $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
  //       curl_close($ch);
		// $data = json_decode($datas, true);
		// return $data;  
		// // if($data['result'] != 0){
		// // 	$shebei['result'] = $data['result'];
		// // 	echo json_encode($shebei);
		// // }else{
		// // 	$shebei = array();
		// // 	$shebei['result'] = $data['result'];          //设备状态 0正常  70003 设备不存在  70006 设备未激活
		// // 	$shebei['device_id'] = $data['device_id'];	    //设备编号
		// // 	$shebei['package_name'] = $data['package_name'];   //套餐名称
		// // 	$shebei['cur_used_flow'] = $data['cur_used_flow'];  //当前套餐已用流量（MB）
		// // 	$shebei['cur_month_used_flow'] = $data['cur_month_used_flow'];  //当月已用流量（MB） 
		// // 	$shebei['cur_expire_date'] = $data['cur_expire_date'];   //当前套餐有效期
			
		// // 	echo json_encode($shebei);
		// // }
  //   }

	/**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */
  //   function get_to_device() {
  //       $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		// $device_id = $this->input->get('device_id');
     
		// $get_device_info_url_api_where = array('name' => 'get_device_info_url');
		// $get_device_info_uid_api_where = array('name' => 'uid');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		// $uid  = $this->Config_m->select($get_device_info_uid_api_where);
		// $signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  //      	$uid = $uid[0]['value']; 
  //      	$signkey = $signkey[0]['value'];
       	
  //       $url = $get_device_info_url;	
  //       $time = 	time();
        
  //       $post_data['password']         = $signkey;
  //       $post_data['simId']            = $device_id;
  //       //$post_data['simId']            = '8986031748204893516';
  //       $post_data['timestamp']        = $time;
  //       $post_data['username']         = $uid;
  //       $data = 'password'.$post_data['password'].'simId'.$post_data['simId'].'timestamp'.$post_data['timestamp'].'username'.$post_data['username'];

  //       $key = MD5($data);
  //       $keys = substr($key, 0, 16);
		// $post_data['key']      = $keys;
		
  //       //$header[] = 'Content-Type: text/html;charset=UTF-8';
  //       $postUrl  = $url;
  //       $curlPost =  $post_data;
       
        
  //       $ch = curl_init();//初始化curl
  //       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
  //       //curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
  //       curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  //       curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
  //       //curl_setopt($ch, CURLOPT_HEADER, false);
  //       curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
  //       curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
  //       curl_setopt($ch, CURLOPT_POST, true);//post提交方式
  //       curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  //       $datas = curl_exec($ch);//运行curl 当前套餐名称
  //      //print_r($datas);die;
  //       $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
  //       curl_close($ch);
		// $data = json_decode($datas, true);
		
		// if($data['status'] != 0){
		// 	$shebei['result'] = $data['status'];
		// 	echo json_encode($shebei);
		// }else{
		// 	$shebei = array();
		// 	$shebei['result'] = $data['status'];          //设备状态 0正常  70003 设备不存在  70006 设备未激活
		// 	$shebei['device_id'] = $data['data'][0]['simId'];	    //设备编号
		// 	$shebei['package_name'] = $data['data'][0]['pckName'];   //套餐名称
		// 	$shebei['cur_used_flow'] = $data['data'][0]['used'];  //当前套餐已用流量（MB）
		// 	$shebei['cur_expire_date'] = $data['data'][0]['endDate'];   //当前套餐有效期
			
		// 	echo json_encode($shebei);
		// }
  //   }
	
	/**
     * post进行设备递交实名请求
     * @param string shiming_to_device
     * @param array $post_data
     */

  //   function shiming_to_device($device_id){
  //   	//$device_id = $this->input->get('device_id');

  //       $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
  //     	$device_where = array('device_sn' => $device_id);
		// $device_info =  $this->Device_m->select($device_where);//设备号信息
		// $user_id_where = array();
		// if(!empty($device_info[0]['user_id'])){
		// 	$user_id_where = array('user_id' => $device_info[0]['user_id']);
		// }else{
		// 	return false; 
		// }

		// $user_info =  $this->Users_m->select($user_id_where);//用户信息
		// $user_idcard_info =  $this->Model_m->select('users_attributes',$user_id_where);//身份证图片
			
  //     	$length = strlen($device_id);
		// if($length != 16){
		// 	$device_id = "0".$device_id."";
		// }

		// $get_device_info_url_api_where = array('name' => 'shiming_to_device_url');
		// $get_device_info_uid_api_where = array('name' => 'uid');
		// $get_device_info_signkey_api_where = array('name' => 'signkey');

		// $get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		// $uid  = $this->Config_m->select($get_device_info_uid_api_where);
		// $signkeys  = $this->Config_m->select($get_device_info_signkey_api_where);
		
  //       $get_device_info_url = $get_device_info_url[0]['value']; 
  //      	$uid = $uid[0]['value']; 
  //      	$signkey = $signkeys[0]['value'];

  //       $url = $get_device_info_url;

  //       $carid_image_z = '';
  //       $carid_image_f = '';
  //       $carid_image_s = '';

  //       if(!empty($user_idcard_info)){
  //       	$carid_image_z = $user_idcard_info[0]['carid_image_z'];
  //       	$carid_image_f = $user_idcard_info[0]['carid_image_f'];
  //       	$carid_image_s = $user_idcard_info[0]['carid_image_s'];
  //       	$carid_image_z_base64 = $this->base64EncodeImage($carid_image_z);
  //       	$carid_image_f_base64 = $this->base64EncodeImage($carid_image_f);
  //       	$carid_image_s_base64 = $this->base64EncodeImage($carid_image_s);
  //       }

		// if(!empty($carid_image_z) || !empty($carid_image_f) || !empty($carid_image_s) ){
		// 	//数据json化。
		// 	$post_data = '{"id":"'.$uid.'","ts":"'.time().'","device_id":"'.$device_id.'","id_num":"'.$user_info[0]['carid'].'","realname":"'.$user_info[0]['realname'].'","addr":"0","phone":10000000000,"id_pic_front":"'.$carid_image_z_base64.'","id_pic_back":"'.$carid_image_f_base64.'","id_pic_inhand":"'.$carid_image_s_base64.'"}';
			 
		// 	$sign = hash_hmac('sha512',$post_data,$signkey); //sha512转码
			
	 //        $header[] = 'Content-Type:application/json'; //头文件
	 //        $header[] = 'sign:'.$sign;
	 //        $header[] = 'uid:'.$uid;
	 //        $postUrl  = $url;

	 //        $curlPost = urlencode($post_data);
	        
	 //        $ch = curl_init();//初始化curl
	 //        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
	 //        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
	 //        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
	 //        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
	 //        //curl_setopt($ch, CURLOPT_HEADER, false);
	 //        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
	 //        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
	 //        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
	 //        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
	 //        $datas = curl_exec($ch);//运行curl 当前套餐名称
	 //        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
	 //        curl_close($ch);
		// 	$data = json_decode($datas, true);
		// 	return $data; 
		// }
		

  //   } 


	function base64EncodeImage($image_file) {
	  $base64_image = '';
	  $image_info = getimagesize($image_file);
	  $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
	  $base64_image = base64_encode($image_data);
	  return $base64_image;
	}

	/**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */

    function chaxun_to_device($device_id) {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		//$device_id = $this->input->get('device_id');
      	$length = strlen($device_id);
		if($length != 16){
			$device_id = "0".$device_id."";
		}

		$get_device_info_url_api_where = array('name' => 'get_device_info_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $get_device_info_url = $get_device_info_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url = $get_device_info_url;

        $post_data['id']         = $uid;
        $post_data['ts']         = time();
        $post_data['device_id']  = $device_id;
		
        $sign = hash_hmac('sha512', _echo($post_data), $signkey);
        $header[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
        $header[] = 'sign:'.$sign;
        $header[] = 'uid:'.$uid;
        $postUrl  = $url;
        $curlPost = _echo($post_data);
        
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data;  
    }
	

	/**
     * post进行套餐查询url请求
     * @param string $url
     * @param array $post_data
     */
    function taocan_to_device() {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		$device_id = $this->input->get('device_id');

		$get_device_info_url_api_where = array('name' => 'taocan_to_device_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$taocan_to_device_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $taocan_to_device_url = $taocan_to_device_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url                           = $taocan_to_device_url;	
        $time                          = time();
        $post_data['password']         = $signkey;
        $post_data['timestamp']        = $time;
        $post_data['username']         = $uid;

        $data = 'password'.$post_data['password'].'timestamp'.$post_data['timestamp'].'username'.$post_data['username'];
        $key = MD5($data);
        $keys = substr($key, 0, 16);
		$post_data['key']      = $keys;
		
        //$header[] = 'Content-Type: text/html;charset=UTF-8';
        $postUrl  = $url;
        $curlPost =  $post_data;
      // print_r($curlPost);die;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
       // curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
		print_r($datas);die;
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data; 
    }

    /**
     * 发送阿里云短信
     * @param string $url
     * @param array $post_data
     */
    function sendsmsgo($mobile,$nickname,$taocan,$lastday){
    	$SmsDemo = new SmsDemo();
    	// 调用示例：
		//set_time_limit(0);
		//header('Content-Type: text/plain; charset=utf-8');

		$response = $SmsDemo->sendSms($mobile,$nickname,$taocan,$lastday);
		// echo "发送短信(sendSms)接口返回的结果:\n";
		// print_r($response);

		// sleep(2);

		// $response = $SmsDemo->querySendDetails();
		// echo "查询短信发送情况(querySendDetails)接口返回的结果:\n";
		// print_r($response);
    }

	//加密解密测试方法 
	function ssencode() {
		$content = "1";
		$mifen = jiami($content);
		//echo "string : " . $content . " <br />";
		echo "encode : " . (jiami($content)) . '<br />';
		echo "name : " . (jiemi($mifen)) . '<br />';
	}


}
    

